package com.sm.controller;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.sm.dao.IManangerDao;
import com.sm.model.Manager;
import com.sm.utils.StringUtils;

@Controller
@RequestMapping("login")
public class LoginController {

	@Autowired
	private IManangerDao iManagerDao;
	
	/**
	 * 登录处理业务
	 */
	@RequestMapping(value = "/checkinto", method = RequestMethod.POST)
	public ModelAndView checkInto(HttpServletRequest req,HttpServletResponse resp,Model model) {
		// 获取session
		HttpSession session = req.getSession();

		String username = req.getParameter("username").trim();
		String password = req.getParameter("password").trim();
		String imageValue = req.getParameter("imageValue");
		String remember = req.getParameter("remember");
		req.setAttribute("username", username);
		req.setAttribute("password", password);
		req.setAttribute("imageValue", imageValue);

		String sRand = (String) session.getAttribute("sRand");

		ModelAndView modelAndView = new ModelAndView();
		
		
		// 这个项目原来已经有人写过了是基于servlet 和 jdbc的
		// 在这个项目中我更多的是带大家一块使用SpringMVC Mybatis
		if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
			modelAndView.setViewName("login");
		}
		if(StringUtils.isEmpty(imageValue)){
	 		req.setAttribute("error", "请输入验证码！");
	 		modelAndView.setViewName("login");

		} else if(!imageValue.equals(sRand)){
			req.setAttribute("error", "验证码错误！");
			modelAndView.setViewName("login");
		}
		
		Manager user=new Manager(username,password);
		session.setAttribute("username", username);
		Manager manager = iManagerDao.isLogin(user);
		if(manager !=null) {
			if("remember-me".equals(remember)){
				rememberMe(username,password,resp);
			}
			modelAndView.setViewName("main");
		} else{
			req.setAttribute("error", "用户名或密码错误!");
			modelAndView.setViewName("login");
		}
		return modelAndView;
	}

	
	private void rememberMe(String userName,String password,HttpServletResponse response){
		Cookie user;
		try {
			user = new Cookie("user",URLEncoder.encode(userName,"UTF-8")+"-"+URLEncoder.encode(password,"UTF-8"));
			user.setMaxAge(1*60*60*24*7);
			response.addCookie(user);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
